import { getToken } from "@/utils";
import EventBus from "@/utils/events";
import axios from "axios";
import qs from "qs";

const requestInstance = axios.create({});

requestInstance.interceptors.request.use((config) => {
  config.paramsSerializer = (params) => {
    return qs.stringify(params, { arrayFormat: "repeat" });
  };
  const isToken = (config.headers || {}).isToken === false;
  if (getToken() && !isToken) {
    config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.headers.Accept = "application/json";
  config.headers["Content-Type"] = "application/json";
  config.headers["X-Requested-With"] = "XMLHttpRequest";
  if (!config.data) config.data = {};
  return config;
});

requestInstance.interceptors.response.use(
  (response) => {
    if(response.data.code !== 200){
      EventBus.emit("global_requet_error", response.data.message);
    }
    return response;
  },
  (error) => {
    const { response } = error;
    // 请求拦截
    if (response.status === 401) {
      EventBus.emit("global_not_login", response.data.message);
    } else if (response.status === 403) {
      EventBus.emit("global_error_auth", "没有权限，别瞎访问");
    }

    return error;
  }
);
export default requestInstance;
